/**
 * @summary: 个人主页，销假申请
 * @author: lixinxiang@vv.cn
 */

import React from 'react';
import { Form, Input, Button, DatePicker, Spin, message } from 'antd';
import FileUpload from '@/components/Custom/FileUpload';
import { submitmyprocessapply, savemyprocessapply } from '@/services/flowMine/apply';
import { history } from 'umi'
import { BottomAction } from '@/components';
import { FlowDescription, ApprovalProgress } from '../components';
import { SelectLeave } from '../components/Select';
import { useProcessList } from '../hooks';

const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 10 }
    }
};

const requiredRule = [
    {
        required: true,
        message: '请输入完整的必填项'
    }
];

const rules = {
    applicationLeaveNo: requiredRule,
    leaveCancelReason: [
        ...requiredRule,
        {
            min: 2,
            max: 200,
            message: '只能输入2--200个字符'
        }
    ]
};

const ResumeLeave = ({ shcema, detail = {}, location, form, onlyShowForm }) => {
    const { query } = location;
    const { formDeploymentId, id, processDeploymentId, templateId, templateName, reedit } = query;
    /* 请假信息 */
    const [leaveDetail, setLeaveDetail] = React.useState({ startTime: '', endTime: '', leaveLong: 0 });

    /* 获取流程数据 */
    // TODO： 之前流程设计有问题，先不考虑性能问题。该方法临时解决流程审批不同步问题。后续整体流程需优化
    const [progressLoading, progress] = useProcessList(
        JSON.stringify({
            applicationLeaveNo: leaveDetail.applicationNo,
            startTime: leaveDetail.startTime,
            endTime: leaveDetail.endTime,
            leaveType: leaveDetail.leaveCode,
            leaveTypeName: leaveDetail.leaveName,
            duration: leaveDetail.leaveLong,
            attachment: ''
        }),
        processDeploymentId
    );

    // 注意：reedit 所有工作流程被退回，重新编辑时，保存按钮需隐藏。

    React.useEffect(() => {
        const { formValueJson = {} } = detail;
        const { applicationLeaveNo = '', leaveCancelReason, attachment } = formValueJson;
        /* 从销假详情里获取请假单号等信息 */
        if (applicationLeaveNo !== '') {
            form.setFieldsValue({ applicationNo: applicationLeaveNo, leaveCancelReason, attachment });
        }
    }, [detail]);

    /* 从 URL 参数中获取请假单号 */
    React.useEffect(() => {
        const finalApplicationNo = query.applicationNo || '';
        if (!finalApplicationNo.includes('LEAVECANCEL')) {
            form.setFieldsValue({ applicationNo: finalApplicationNo });
        }
    }, []);

    const handleSubmit = React.useCallback(
        isSave => async e => {
            e.preventDefault();

            const { attachment = {}, leaveCancelReason } = form.getFieldsValue();
            const {
                applicationNo = '',
                leaveCode = '',
                leaveName = '',
                startTime = '',
                endTime = '',
                leaveLong = 0
            } = leaveDetail;

            const params = {
                id,
                formDeploymentId,
                templateId,
                templateName,
                processDeploymentId,
                formValueJson: JSON.stringify({
                    applicationLeaveNo: applicationNo,
                    leaveCancelReason,
                    startTime,
                    endTime,
                    leaveType: leaveCode,
                    leaveTypeName: leaveName,
                    duration: leaveLong,
                    attachment: ''
                }),
                resourceRelation: attachment.uploadResourceFile ? [attachment.uploadResourceFile] : []
            };

            if (!isSave) {
                form.validateFields(async err => {
                    if (!err) {
                        await submitmyprocessapply(params);
                        history.push({
                            pathname: '/personal/portal/flow/mine/myApplication'
                        });
                    }
                });
            } else {
                if (!applicationNo && !leaveCancelReason) {
                    message.error('您还没有输入，请输入任一必填内容即可保存！');
                    return;
                }
                await savemyprocessapply(params);
                history.push({
                    pathname: '/personal/portal/flow/mine/myApplication'
                });
            }
        },
        [leaveDetail, form]
    );

    const handleSelectLeave = React.useCallback((_value, row = {}) => {
        form.setFieldsValue({ applicationNo: _value });
        setLeaveDetail(row);
    }, []);

    return (
        <div style={{ marginTop: onlyShowForm ? 0 : 24 }}>
            <FlowDescription description={shcema.description} />
            <Form style={{ marginTop: 24 }} {...formItemLayout}>
                <Form.Item label="请选择请假记录" extra="有效范围为发起销假申请的前3个月内，未来不限期">
                    {form.getFieldDecorator('applicationNo', { rules: rules.applicationLeaveNo, trigger: 'onBlur' })(
                        <SelectLeave
                            placeholder="请选择请假记录"
                            disabled={onlyShowForm}
                            onChange={handleSelectLeave}
                        />
                    )}
                </Form.Item>

                {!onlyShowForm && leaveDetail.startTime && (
                    <>
                        <Form.Item label="开始时间">
                            <DatePicker style={{ width: '100%' }} placeholder={leaveDetail.startTime} disabled />
                        </Form.Item>

                        <Form.Item label="结束时间">
                            <DatePicker style={{ width: '100%' }} placeholder={leaveDetail.endTime} disabled />
                        </Form.Item>

                        <Form.Item label="时长" extra="审批通过后请假时长将自动从考勤统计销除">
                            <Input placeholder={`${leaveDetail.leaveLong / 60} 小时`} disabled />
                        </Form.Item>
                    </>
                )}

                <Form.Item label="销假理由" extra="2-200字">
                    {form.getFieldDecorator('leaveCancelReason', { rules: rules.leaveCancelReason })(
                        <Input.TextArea rows={4} placeholder="请输入销假理由" disabled={onlyShowForm} />
                    )}
                </Form.Item>

                <Form.Item label="附件">
                    {form.getFieldDecorator('attachment')(<FileUpload disabled={onlyShowForm} />)}
                </Form.Item>

                {!onlyShowForm && (
                    <>
                        <Spin spinning={progressLoading}>
                            <ApprovalProgress progress={progress} />
                        </Spin>

                        <BottomAction>
                            {!reedit && (
                                <Button onClick={handleSubmit(true)} style={{ marginLeft: 12 }} disabled={onlyShowForm}>
                                    保存
                                </Button>
                            )}
                            <Button type="primary" onClick={handleSubmit(false)} disabled={onlyShowForm}>
                                提交
                            </Button>
                        </BottomAction>
                    </>
                )}
            </Form>
        </div>
    );
};

const FormResumeLeave = Form.create({ name: 'ResumeLeave' })(ResumeLeave);
export default FormResumeLeave;
